package com.jhhc.Config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.jhhc.BDMS.System.Serivce.BDMS_POWER_BService;
import com.jhhc.BDMS.System.entity.BDMS_POWER_B;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Util.TimeUtil;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Util.WindSiteUtil;
import com.jhhc.utils.JsonResult;
import com.jhhc.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author LYQ
 */
@Component
@RequiredArgsConstructor
public class Interceptor implements HandlerInterceptor {

    private final BDMS_POWER_BService bdmsPowerBService;

    private final RedisUtil redisUtil;

    private final TimeUtil timeUtil = new TimeUtil();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在请求处理之前执行的逻辑
//        System.out.println("请求方式:" + request.getMethod() + "<br/>" +
//                "客户端的 IP 地址:" + request.getRemoteAddr() + "<br/>" +
//                "应用名字(上下文):" + request.getContextPath() + "<br/>" +
//                "URI:" + request.getRequestURI() + "<br/>" +
//                "请求字符串:" + request.getQueryString() + "<br/>" +
//                "Servlet所映射的路径:" + request.getServletPath() + "<br/>" +
//                "客户端的完整主机名:" + request.getRemoteHost() + "<br/>");
//        PrintWriter writer = response.getWriter();
//        Enumeration<String> headers = request.getHeaderNames();
//        while (headers.hasMoreElements()) {
//            //获得请求头字段的值
//            String value = request.getHeader(headers.nextElement());
//            writer.write(headers.nextElement() + ":" + value + "<br/>");
//        }

        //9.获取post和get两种请求参数
//        response.setHeader("content-type", "text/json;charset=utf-8");
//        //String token = request.getHeader("token");
//        String pid = null;
//        JSONArray stationCodes = null;
//        if ("POST".equalsIgnoreCase(request.getMethod())) {
//            JSONObject body = JSON.parseObject(request.getInputStream(),JSONObject.class);
//            if (body != null) {
//                System.out.printf("body:%s\n",JSON.toJSONString(body, String.valueOf(true)));
//                pid = body.getString("projectId");
//                stationCodes = body.getJSONArray("stationCodes");
//                if (stationCodes != null) {
//                    String code = null;
//                    for (int i = 0; i < stationCodes.size(); i++) {
//                        code = stationCodes.getString(i);
//                        if ("70800001".equals(code) || "70800002".equals(code) || "70800003".equals(code) || "70800004".equals(code)
//                                || "70800005".equals(code) || "70800006".equals(code) || "70800007".equals(code) || "70800008".equals(code)
//                                || "70800009".equals(code) || "70800010".equals(code)) {
//                            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//                            response.getWriter().write(JSON.toJSONString(JsonResult.getJson("网络错误")));
//                            return false;
//                        }
//                    }
//                }
//            }
//        }else {
//            pid = request.getParameter("projectId");
//            Map<String,String[]> map = request.getParameterMap();
//            String[] codes = map.get("stationCodes");
//            if (codes != null) {
//                for (String code : codes) {
//                    if ("70800001".equals(code) || "70800002".equals(code) || "70800003".equals(code) || "70800004".equals(code)
//                            || "70800005".equals(code) || "70800006".equals(code) || "70800007".equals(code) || "70800008".equals(code)
//                            || "70800009".equals(code) || "70800010".equals(code)) {
//                        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//                        response.getWriter().write(JSON.toJSONString(JsonResult.getJson("网络错误")));
//                        return false;
//                    }
//                }
//            }
//        }
//        if (pid == null || pid.isEmpty()) {
//            return true;
//        }else {
//            List<BDMS_POWER_B> bdmsPowerBs = bdmsPowerBService.queryAll(pid);
//            Map<Integer,List<BDMS_POWER_B>> map = bdmsPowerBs.stream().filter(Objects::nonNull).collect(Collectors.groupingBy(BDMS_POWER_B::getPid));
//            switch (pid){
//                case "220103":
//                    //温州
//                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//                    response.getWriter().write(JSON.toJSONString(JsonResult.getJson("网络错误")));
//                    return false;
//                case "230101":
//                    String time = WindSiteUtil.decrypt(map.get(Integer.parseInt(pid)).get(0).getValidtime(),"RiverStrongJhhc.");
//                    //boolean flag = Boolean.parseBoolean(WindSiteUtil.decrypt(map.get(Integer.parseInt(pid)).get(0).getHasAlidation(),"RiverStrongJhhc."));
//                    if (timeUtil.compareTime(timeUtil.currentTime(),time) > 0) {
//                        return true;
//                    }else {
//                        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//                        response.getWriter().write(JSON.toJSONString(JsonResult.getJson("网络错误")));
//                        return false;
//                    }
//                default:
//                    return true;
//            }
//        }
        return true;
    }
//    private String getBody(ContentCachingRequestWrapper request) throws UnsupportedEncodingException {
//        byte[] body = request.getContentAsByteArray();
//        return new String(body, 0, body.length, request.getCharacterEncoding());
//    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 在请求处理之后执行的逻辑，视图渲染之前
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在整个请求处理完成后执行的逻辑，包括视图渲染之后
    }
}
